package com.gyx.lottery.common.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import org.springframework.boot.json.JsonParseException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {
    private JacksonUtil() {

    }
    //单例模式
    private static final ObjectMapper OBJECT_MAPPER;
    static {
        OBJECT_MAPPER=new ObjectMapper();
    }
    private static ObjectMapper getObjectMapper(){return OBJECT_MAPPER;}
    public static <T> T tryParse(Callable<T>parser){return tryParse(parser, JacksonException.class);}
    private static <T> T tryParse(Callable<T>parser,Class<? extends Exception>check){
        try{
            return  parser.call();
        }catch (Exception var4){
            if(check.isAssignableFrom(var4.getClass())){
                throw new JsonParseException(var4);
            }
            throw new IllegalStateException(var4);
        }
    }
    //序列化，反序列化
    public static String writeVauleAsString(Object object){
        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().writeValueAsString(object);
        });
    }
    //反序列化
    public static <T> T readVaule(String content,Class<T>valueType){
        return JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().readValue(content,valueType);
        });

    }
    public static <T> T readListValue(String content,Class valueType){
        JavaType javaType=JacksonUtil.getObjectMapper().getTypeFactory()
                .constructParametricType(List.class,valueType);
        return  JacksonUtil.tryParse(()->{
            return JacksonUtil.getObjectMapper().readValue(content,javaType);
        });
    }

}
